<template>
  <base-breadcrumb :title="titleName">
    <a-row :gutter="10" class="page-height">
      <!-- 树搜索 -->
      <a-col :span="6" class="permission-collapsed" :class="{ 'permission-tree-collapsed': collapsed }">
        <a-card :style="{ border: collapsed ? 'none' : 'border: 1px solid #e8e8e8' }" class="page-height-tree">
          <title-name title="组织架构" />
          <PermissionTreeOrganization :collapsed.sync="collapsed" @select="handleSelect" />
        </a-card>
      </a-col>
      <!-- 树搜索 -->
      <a-col :span="18" class="permission-collapsed page-height-list-wrapper"
        :style="collapsed ? 'width:calc(100% - 10px)' : ''">
        <searchData :search-data="searchArr" @search="search" />
        <a-card :bordered="false" class="page-height-list">
          <div class="table-operator">
            <a-button
              v-btnPermission="[{ code: 'seex_pm_001_add_10', ident: 'prma_seex' }, { code: 'buco_pm_001_add_10', ident: 'prma_buco' }]"
              type="primary" icon="plus" @click="handleAdd">
              新增项目
            </a-button>
          </div>
          <div class="pub-table-select-count">
            <a-icon type="info-circle" theme="twoTone" />
            <span style="margin-right: 12px">
              <!--已选择：<span class="totalNum">{{selectedNum}} </span> 项 |-->
              项目总共：<span class="totalNum">{{ totalNum }} </span> 项
            </span>
          </div>
          <list-table ref="table" size="default" :row-key="(record) => record.projectId" :columns="columns"
            :request="loadData" :alert="true" show-size-changer show-quick-jumper show-pagination="auto">
            <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
            <span slot="projectName" slot-scope="text">
              <ellipsis :length="20" tooltip>{{ text }}</ellipsis>
            </span>
            <span slot="projectAddress" slot-scope="text">
              <ellipsis :length="20" tooltip>{{ text }}</ellipsis>
            </span>
            <span slot="majorCustomerName" slot-scope="text">
              <ellipsis :length="20" tooltip>{{ text }}</ellipsis>
            </span>
            <span slot="projectNum" slot-scope="text, record">
              <span v-if="record.projectNum == '' || record.projectNum == null" style="color: #dcdcdc; font-size: 14px">
                待定</span>
              <span v-else> {{ record.projectNum }}</span>
            </span>
            <span slot="projectTime" slot-scope="text, record">
              <template> {{ record.contractStartDate }}—{{ record.contractFinishDate }} </template>
            </span>
            <span slot="projectFormat" slot-scope="text, record">
              <template>
                {{ record.projectFormat && record.projectFormat.join('&') }}
              </template>
            </span>
            <span slot="action" slot-scope="text, record">
              <MoreButton>
                <a v-btnPermission="[{ code: 'seex_pm_001_loo_11', ident: 'prma_seex' }, { code: 'buco_pm_001_loo_11', ident: 'prma_buco' }]"
                  @click="handleSub(record)">查看</a>
                <template
                  v-if="JSON.parse(record.epcIsInnerProject) && record.statusCode !== '0' && record.statusCode !== '2'">
                  <a v-btnPermission="'pm_001_moi_26'" @click="hadnleApprova(record)">审批信息</a>
                </template>
                <template v-if="record.statusCode == '0' || record.statusCode == '2' || record.statusCode == '3'">
                  <a v-btnPermission="[{ code: 'seex_pm_001_edi_12', ident: 'prma_seex' }, { code: 'buco_pm_001_edi_12', ident: 'prma_buco' }]"
                    @click="handleEdit(record)">编辑</a>
                </template>
                <!-- 没有此功能 -->
                <!-- <span v-if="!(JSON.parse(record.epcIsInnerProject)) &&(record.statusCode == '0' || record.statusCode == '3')">
                  <a-divider type="vertical" /><a @click="handleApprove(record)">提交审批</a>
                </span> -->
                <!-- 没有此功能 -->
                <template v-if="record.statusCode == '4' && hideBuquBtn()">
                  <a @click="handleSetup(record)">开工设置</a>
                </template>
                <span v-if="parseInt(record.statusCode) === 5"
                  v-btnPermission="[{ code: 'seex_pm_001_yun_25', ident: 'prma_seex' }, { code: 'buco_pm_001_yun_25', ident: 'prma_buco' }]">
                  <a @click="handleYzCode(record)">云筑项目编码</a>
                </span>
                <!--<span v-if="record.signingContract == '否' && record.statusCode != '0' && record.statusCode != '1'&& record.statusCode != '3' && record.statusCode != '4' "><a-divider type="vertical"/><a @click="handleContractEdit(record)">合同信息编辑</a></span>-->
              </MoreButton>
            </span>
          </list-table>
        </a-card>
      </a-col>
    </a-row>
    <ChangeCmportanceOrCode :visible.sync="cmportanceVisible" :type="cmportanceType" :data="cmportanceData"
      @update="list()" />
  </base-breadcrumb>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import { projectsAudit, projectsStarts, getProSubProjectTotal, getProSubProjectsList, getProjectFrom } from '@/api/project/projects'
// import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司选择框
import SelectProjectFormat from '@/components/Select/SelectProjectFormat' // 项目业态选择框
import ChangeCmportanceOrCode from '../components/ChangeCmportanceOrCode'
import ARow from 'ant-design-vue/es/grid/Row'
import PermissionTreeOrganization from '@/components/businessComponents/PermissionTreeOrganization'
import MoreButton from '@/components/MoreButton'
import { getImportantsList } from '@/api/project/importants'
const columns = [
  {
    title: '序号',
    width: 65,

    scopedSlots: { customRender: 'serial' }
  },
  // {
  //   title: '项目编号',
  //   dataIndex: 'projectNum',
  //   width: 120,
  //   scopedSlots: { customRender: 'projectNum' }
  // },
  {
    title: '项目备案名称',
    width: 200,
    dataIndex: 'projectName',
    ellipsis: true
    // scopedSlots: { customRender: 'projectName' }
  },
  {
    title: '项目简称',
    width: 200,
    dataIndex: 'shortName',
    ellipsis: true
  },
  {
    title: '项目业态',
    dataIndex: 'projectFormat'
    // scopedSlots: { customRender: 'projectFormat' }
  },
  {
    title: '分公司',
    width: 120,
    dataIndex: 'branchName'
  },
  {
    title: '项目地点',
    dataIndex: 'projectAddress',
    width: 200
    // scopedSlots: { customRender: 'projectAddress' }
  },
  {
    title: '项目重要程度',
    dataIndex: 'projectImportanceName'
  },
  {
    title: '公司级大客户',
    width: 200,
    dataIndex: 'majorCustomerName'
    // scopedSlots: { customRender: 'majorCustomerName' }
  },
  {
    title: '专业项目经理',
    width: 120,
    dataIndex: 'projectManagerName'
  },
  {
    title: '合同工期(天)',
    width: 80,
    dataIndex: 'projectContractCycle'
  },
  {
    title: '合同开竣工时间',
    dataIndex: 'projectTime',
    width: 140,
    scopedSlots: { customRender: 'projectTime' }
  },
  {
    title: '立项时间',
    dataIndex: 'projectCreateTime',
    width: 120
  },
  {
    title: '状态',
    width: 140,
    dataIndex: 'statusName'
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 200,
    fixed: 'right',
    scopedSlots: { customRender: 'action' }
  }
]

const statusMap = {
  0: {
    status: 'default',
    text: '关闭'
  },
  1: {
    status: 'processing',
    text: '运行中'
  },
  2: {
    status: 'success',
    text: '已上线'
  },
  3: {
    status: 'error',
    text: '异常'
  }
}

export default {
  name: 'a' + Date.now(),
  props: {
    editType: {
      type: String
    }
  },
  components: {
    STable,
    Ellipsis,
    PermissionTreeOrganization,
    ChangeCmportanceOrCode,
    MoreButton
  },
  data() {
    this.columns = columns
    return {
      spinning: false,
      expand: true,
      onlyCompany: 1,
      cmportanceVisible: false,
      // 变更重要程度或者项目编码模态框类型
      cmportanceType: 0,
      // 变更重要程度或者项目编码模态框数据
      cmportanceData: {},
      searchArr: [
        // 搜索框
        {
          name: '项目备案名称',
          value: 'projectName',
          type: 'input'
        },
        {
          name: '项目业态',
          value: 'projectFormat',
          type: 'select',
          data: []
        },
        {
          name: '项目重要程度',
          value: 'projectImportanceName',
          type: 'select',
          data: [],
        },
        {
          name: '状态',
          value: 'projectStatusQuery',
          type: 'selectMode',
          data: [
            {
              value: 'DRAFT',
              label: '待提交'
            },
            {
              value: 'SUBMITTED',
              label: '审批中'
            },
            {
              value: 'REJECTED',
              label: '审批不通过'
            },
            {
              value: 'IN_THE_PROJECT',
              label: '待立项'
            },
            {
              value: 'ONGOING',
              label: '施工准备阶段'
            },
            {
              value: 'START_WORKING',
              label: '在建'
            },
            {
              value: 'SHUTDOWN',
              label: '停工'
            },
            {
              value: 'SUSPENDED',
              label: '停缓建'
            },
            {
              value: 'MAINTENANCE_PERIOD',
              label: '维保期'
            },
            {
              value: 'COMPLETE',
              label: '维保期截止'
            },
          ]
        }
        // {
        //   name: '分公司',
        //   valueKey: 'branchCode',
        //   type: SelectSubCompany
        // }
      ],
      titleName: '',
      loadData: (parameter) => {
        this.queryParam.branchCode = undefined
        this.queryParam.projectId = this.select.projectId || undefined
        if (this.select.tageCode === 'BC') {
          this.queryParam.branchCode = this.select.orgId
        }
        //businessType 业务类型（1：项目列表，2：专业项目列表）
        const requestParameters = Object.assign({ statusSet: [0, 1, 2, 3, 4, 5, 6], auditStatusSet: [0, 1, 2, 3], businessType: 2 }, parameter, this.queryParam)
        return getProSubProjectsList(requestParameters).then((res) => {
          this.totalNum = res.totalSize
          return res
        })
      },
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      selectedRowKeys: [],
      selectedRows: [],
      selectedNum: 0,
      totalNum: '',
      totalDels: {},
      //组织架构选中项
      select: {},
      // 收缩展开树
      collapsed: false
    }
  },
  filters: {
    statusFilter(type) {
      return statusMap[type].text
    },
    statusTypeFilter(type) {
      return statusMap[type].status
    }
  },
  created() {
    this.getProjectTotal()
    this.getProjectFrom()
    this.getImportantsList()
  },
  computed: {
    // rowSelection() {
    //   return {
    //     selectedRowKeys: this.selectedRowKeys,
    //     selectedRows: this.selectedRows,   // 当前行所有数据
    //     onChange: this.onSelectChange
    //   }
    // },
  },
  methods: {
    list(params, callback) {
      this.$refs.table.refresh()
    },
    /**
     * @description: 云筑项目编码
     * @param {object} record 行数据
     * @return {void}
     */
    handleYzCode(record) {
      this.cmportanceVisible = true
      this.cmportanceType = 2
      this.cmportanceData = record
    },
    /**
     * @description: 树选中
     * @param {object} node 节点对象
     * @return {void}
     */
    handleSelect(node) {
      this.select = node
      this.$refs.table.refresh(true)
    },
    getProjectFrom() {
      getProjectFrom().then((res) => {
        this.searchArr[1].data = this.getLabelData(res.data)
      })
    },
    getProjectTotal() {
      getProSubProjectTotal(this.queryParam).then((res) => {
        this.totalDels = res.data
      })
    },
    handleApprove(val) {
      let that = this
      that.$confirm({
        title: '是否确定提交立项审批?',
        content: '',
        onOk() {
          return new Promise((resolve, reject) => {
            let data = { id: val.projectId }
            projectsAudit(data)
              .then((res) => {
                if (res.data.code == 200) {
                  that.$message.success('审批成功！')
                  that.$refs.table.refresh(true)
                } else {
                  that.$message.error('审批失败！')
                }
              })
              .catch((e) => {
                that.$message.error(e)
              })
              .finally(() => {
                resolve()
              })
          })
        },
        onCancel() { }
      })
    },

    handleSetup(val) {
      let that = this
      this.$confirm({
        title: '是否将项目状态更改为 "在建" 状态?',
        content: '',
        onOk() {
          projectsStarts({ id: val.projectId }).then((res) => {
            if (res.data.code == 200) {
              that.$message.success('在建状态设置成功！')
              that.$refs.table.refresh(true)
            }
          })
        },
        onCancel() { }
      })
    },

    search(values) {
      this.queryParam = values
      this.getProjectTotal()
      this.$refs.table.refresh(true)
    },

    resetSearch() {
      this.queryParam = {}
    },
    searchData() {
      // 搜索
      this.$refs.table.refresh(true)
    },
    deletes() { },
    handleAdd() {
      this.$router.push('/project/addProjects/add')
    },
    handleEdit(record) {
      if (JSON.parse(record.epcIsInnerProject)) {
        this.$router.push({ path: '/project/addProjects/edit', query: { projectId: record.projectId } })
      } else {
        this.$router.push({ path: '/install/update', query: { projectId: record.projectId, branchCode: '1' } })
      }

      // if(record.branchBusinessEnumCode == null){
      //   this.$router.push({path:'/project/addProjects',query: {projectId:record.projectId}})
      // } else{
      //   this.$router.push({path:'/install/update',query: {projectId:record.projectId,branchCode:record.branchBusinessEnumCode}})
      // }
    },
    handleOk() {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('values', values)
          if (values.id > 0) {
            new Promise((resolve, reject) => {
              setTimeout(() => {
                resolve()
              }, 1000)
            }).then((res) => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.info('修改成功')
            })
          } else {
            // 新增
            new Promise((resolve, reject) => {
              setTimeout(() => {
                resolve()
              }, 1000)
            }).then((res) => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.info('新增成功')
            })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleSub(record) {
      this.$router.push({ path: '/project/details', query: { projectId: record.projectId, isDetails: 1 } })
    },
    handleContractEdit(val) {
      // 合同信息编辑
      this.$router.push({ path: '/project/contractInfo', query: { projectId: val.projectId } })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedNum = selectedRowKeys.length

      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    /**
     * @description: 审批信息
     * @param {object} record
     * @return {void}
     */
    hadnleApprova(record) {
      this.$bus.$emit('showApprovalDetailsDialog', record.projectId)
    },
    getImportantsList() {
      getImportantsList({ importantStatusCode: 1 }).then((res) => {
        res.data.map((item)=> {
          item.label = item.importantName
          item.value = item.importantId
        })
        this.searchArr[2].data = res.data;
      })
    },
  }
}
</script>

